package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.CgtCustService;
import com.lt.test.common.emchat.Emchat;
import com.lt.test.common.exception.CustomException;
import com.lt.test.common.util.CustomUtil;
import com.lt.test.entity.DTO.CgtCustDTO;
import com.lt.test.entity.DTO.DCust2MemberDTO;
import com.lt.test.entity.DTO.PageDTO;
import com.lt.test.entity.QueryModel.PageFilter;
import com.lt.test.entity.QueryModel.PageQueryModel;
import com.lt.test.provider.mapper.CgtCustCustomMapper;
import com.lt.test.provider.mapper.DCust2MemberCustomMapper;
import com.lt.test.provider.mapper.UserMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(version = "1.0.0")
public class CgtCustServiceImpl implements CgtCustService {
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	@Resource
	private CgtCustCustomMapper cgtCustCustomMapper;
	@Resource
	private DCust2MemberCustomMapper dCust2MemberCustomMapper;
	@Resource
	private UserMapper userMapper;
	@Override
	public PageDTO<CgtCustDTO> findCgtCustByPage(Integer page, Integer pageSize, String sortedKey, String sortedValue,
												 String filters, Map<String, String> params) throws CustomException {
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;
		
		PageQueryModel pageQueryModel = new PageQueryModel();
		pageQueryModel.setBeginNum(beginNum);
		pageQueryModel.setEndNum(endNum);
		
		if("orderDateStr".equals(sortedKey)) {
			pageQueryModel.setSortName("CC.ORDER_DATE");
		}else if ("bankCarCount".equals(sortedKey)) {
			pageQueryModel.setSortName("CC.BANK_CAR_COUNT");
		}else if ("orderCOunt".equals(sortedKey)) {
			pageQueryModel.setSortName("CC.COUNT_ORDER");
		}else if ("firstBindCarTime".equals(sortedKey)) {
			pageQueryModel.setSortName("CC.FIRST_BIND_CAR_TIME");
		}else if ("firstPayOrderTime".equals(sortedKey)) {
			pageQueryModel.setSortName("CC.FIRST_PAY_ORDER_TIME");
		}else if ("firstLoginTime".equals(sortedKey)) {
			pageQueryModel.setSortName("CC.FIRST_LOGIN_TIME");
		}
		else {
			pageQueryModel.setSortName("CC.CHANNEL_NAME");
		}
		pageQueryModel.setSortOrder(("asc".equals(sortedValue) ? "asc" : "desc"));//防止sql注入

		pageQueryModel.setFilters(getCustPageQueryModel(filters,params));

		List<CgtCustDTO> shopDOList = null;
		int recordCount = 0;
		try {
			shopDOList = cgtCustCustomMapper.findCgtCustByPage(pageQueryModel);
			recordCount = cgtCustCustomMapper.getCgtCustCount(pageQueryModel);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("获取烟草客户列表失败");
		}
		PageDTO<CgtCustDTO> result = new PageDTO<>(page, pageSize, shopDOList, recordCount);
		return result;
	}

	@Override
	public List<Map<String, Object>> cgtCustInfoExportExcel(String filters, Map<String, String> params) throws Exception {

		Integer pageSize = Integer.valueOf(params.get("pageSize"));

		Long page = params.get("page") == null ? 1 : Long.valueOf(params.get("page"));

		Long beginNum = ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		PageQueryModel pageQueryModel = new PageQueryModel();
		pageQueryModel.setBeginNum(beginNum);
		pageQueryModel.setEndNum(endNum);



		pageQueryModel.setFilters(getCustPageQueryModel(filters,params));

		return cgtCustCustomMapper.cgtCustInfoExportExcel(pageQueryModel);
	}


	private List<PageFilter> getCustPageQueryModel(String filters, Map<String, String> params) {
		List<PageFilter> filterList = new ArrayList<>();

		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");

			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("quXianName".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.QU_XIAN_NAME");
					filter.setFilterType("=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}
				if("quDaoName".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.CHANNEL_NAME");
					filter.setFilterType("=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}
				if("KeHuJingLiName".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.SLSMAN_NAME");
					filter.setFilterType("=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}

				if("channelName".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.CUST_NAME");
					filter.setFilterType("=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}
				if("slsmanName".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.CUST_CODE");
					filter.setFilterType("=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}
				if("cityType".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.CITY_TYPE");
					filter.setFilterType("=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}
				if("orderLevel".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.CUST_ORDER_LEVEL");
					filter.setFilterType("=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}
				if("firstBindCarTime".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName(result.get("type").toString());
					filter.setFilterType(">=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}

				if("firstPayOrderTime".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))) {
					PageFilter filter = new PageFilter();
					filter.setFilterName(result.get("type").toString());
					filter.setFilterType("<=");
					filter.setFilterValue("'"+result.getString("data")+"'");
					filterList.add(filter);
				}

				if("isBankCar".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data")) && !result.getString("data").equals("-1")){
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.FIRST_BIND_CAR_TIME");
					if (result.getString("data").equals("1")){
						filter.setFilterType("is not ");

					}else {
						filter.setFilterType("is");
					}
					filter.setFilterValue("null");
					filterList.add(filter);
				}

				if("isPay".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data")) && !result.getString("data").equals("-1")){
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.FIRST_PAY_ORDER_TIME");
					if (result.getString("data").equals("1")){
						filter.setFilterType("is not ");

					}else {
						filter.setFilterType("is");
					}
					filter.setFilterValue("null");
					filterList.add(filter);
				}

				if("isDingYan".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data")) && !result.getString("data").equals("-1")){
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.FIRST_RESERVE_TIME");
					if (result.getString("data").equals("1")){
						filter.setFilterType("is not ");

					}else {
						filter.setFilterType("is");
					}
					filter.setFilterValue("null");
					filterList.add(filter);
				}

				if("isExp".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data")) && !result.getString("data").equals("-1")){
					PageFilter filter = new PageFilter();
					filter.setFilterName("CC.IS_EXP");
					if (result.getString("data").equals("1")){
						filter.setFilterType("=");

					}else {
						filter.setFilterType("!=");
					}
					filter.setFilterValue("'是'");
					filterList.add(filter);
				}

				if("syncState".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data")) && !result.getString("data").equals("-1")){
					PageFilter filter = new PageFilter();
					filter.setFilterName("( CC.SYNC_STATUS");
					String isNullFlag = "";
					if (result.getString("data").equals("1")){
						filter.setFilterType("=");

					}else {
						filter.setFilterType("!=");
						isNullFlag = " or CC.SYNC_STATUS IS NULL";
					}
					filter.setFilterValue("01 "+isNullFlag+")");
					filterList.add(filter);
				}
			}
		}

		if(params.get("userQuYu") != null && !"".equals(params.get("userQuYu"))) {
			PageFilter filter = new PageFilter();
			filter.setFilterName("substr(CC.CHANNEL_CODE, 0, 4)");
			filter.setFilterType("=");
			filter.setFilterValue("'"+ CustomUtil.getChannelCodePreFive(params.get("userQuYu"))+"'");
			filterList.add(filter);
		}


		String empName =  params.get("userEmpName");
		if (empName != null && !"".equals(empName)) {
			PageFilter filter = new PageFilter();
			filter.setFilterName("CC.SLSMAN_NAME");
			filter.setFilterType("=");
			filter.setFilterValue("'"+empName+"'");
			filterList.add(filter);
		}

		String userChannelName =  params.get("userChannelName");
		if (userChannelName != null && !"".equals(userChannelName)) {
			PageFilter filter = new PageFilter();
			filter.setFilterName("CC.CHANNEL_NAME");
			filter.setFilterType("=");
			filter.setFilterValue("'"+userChannelName+"'");
			filterList.add(filter);
		}

		String userQuXianName =  params.get("userQuXianName");
		if (userQuXianName != null && !"".equals(userQuXianName)) {
			PageFilter filter = new PageFilter();
			filter.setFilterName("CC.QU_XIAN_NAME");
			filter.setFilterType("=");
			filter.setFilterValue("'"+userQuXianName+"'");
			filterList.add(filter);
		}

		//优化一下查询条件
		boolean hasCustName = false;
		boolean hasEmpName = false;
		boolean hasChannelName = false;
		boolean hasQuXianName = false;

		for (PageFilter filter : filterList) {
			if ("CC.CUST_NAME".equals(filter.getFilterName())){
				hasCustName = true;
			}
			if ("CC.SLSMAN_NAME".equals(filter.getFilterName())){
				hasEmpName = true;
			}
			if ("CC.CHANNEL_NAME".equals(filter.getFilterName())){
				hasChannelName = true;
			}
			if ("CC.QU_XIAN_NAME".equals(filter.getFilterName())){
				hasQuXianName = true;
			}


		}

		if (hasQuXianName) {
			for (PageFilter filter : filterList) {
				if ("substr(CC.CHANNEL_CODE, 0, 4)".equals(filter.getFilterName())) {
					filterList.remove(filter);
					break;
				}
			}
		}
		if (hasChannelName) {
			for (PageFilter filter : filterList) {
				if ("CC.QU_XIAN_NAME".equals(filter.getFilterName())) {
					filterList.remove(filter);
					break;
				}
			}
		}
		if (hasEmpName) {
			for (PageFilter filter : filterList) {
				if ("CC.CHANNEL_NAME".equals(filter.getFilterName())) {
					filterList.remove(filter);
					break;
				}
			}
		}

		if (hasCustName) {
			for (PageFilter filter : filterList) {
				if ("CC.SLSMAN_NAME".equals(filter.getFilterName())) {
					filterList.remove(filter);
					break;
				}
			}
		}

		return filterList;
	}

	@Override
	public PageDTO<DCust2MemberDTO> findSubCgtCustByParentId(String parentId) throws CustomException {
		List<DCust2MemberDTO> cgtCustDTOList = null;
		try {
			cgtCustDTOList = dCust2MemberCustomMapper.findSubCgtCustByParentId(parentId);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("服务器异常");
		}
		return new PageDTO<>(1, 1000, cgtCustDTOList, 1000);
	}
	@Override
	public void accreditCgtCust(String id, String flag) throws CustomException {
		Map<String,String> params = new HashMap<>(2,1.0F);
		params.put("id", id);
		params.put("flag", flag);
		try {
			dCust2MemberCustomMapper.accreditCgtCust(params);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("Dubbo连接错误");
		}
		
	}
	@Override
	public void sendCloudingMessage(String phone, String content) throws CustomException {
		try {
			List<Map<String,String>> userIdAndCloudingIdList  = dCust2MemberCustomMapper.findUserIdAndCloudingIdByPhone(phone);
			Map<String,String> userIdAndCloudingId = userIdAndCloudingIdList.get(0);
			Emchat.sendTextMessage(userIdAndCloudingId.get("cloudingId"), content, userIdAndCloudingId.get("userId"), null);
		} catch(RuntimeException e) {
			e.printStackTrace();
			throw new CustomException("消息发送失败");
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("Dubbo连接异常");
		} 
		
	}

	@Override
	public Map<String, Object> getUserInfo(String custCode) throws CustomException {

		Map<String,Object> result = new HashedMap(4,1.0F);
		try {
			CgtCustDTO cgtCustDTO = cgtCustCustomMapper.getUserBasicInfo(custCode);
			result.put("basicInfo",cgtCustDTO);
			List<DCust2MemberDTO> cgtCustDTOList  = dCust2MemberCustomMapper.findSubCgtCustByParentId(cgtCustDTO.getId().toString());
			result.put("authorizationInfoList",cgtCustDTOList);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("获取用户信息失败");
		}
		return result;
	}
}
